package com.qf.blog.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.blog.web.entity.CommentEntity;
import com.qf.blog.web.entity.UserEntity;
import com.qf.blog.web.mapper.CommentMapper;
import com.qf.blog.web.service.ICommentService;
import com.qf.blog.web.vo.CommentVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentEntity> implements ICommentService {

    @Autowired
    private LikeService likeService;

    @Override
    public boolean save(CommentEntity commentEntity) {
        commentEntity.setCreateTime(new Date());
        commentEntity.setStatus(1);
        return baseMapper.insert(commentEntity) > 0;
    }

    @Override
    public List<CommentVo> commentListByInvitataionId(UserEntity userEntity, Integer id) throws Exception {

        // 1、根据帖子id查询，它下面的一级评论信息和作者信息
        List<CommentVo> commentVoList = baseMapper.commentListByInvitataionId(1, id);

        // 2.循环遍历，查询每一条评论下面的回复
        for (CommentVo commentVo : commentVoList) {

            //查询当前评论的点赞数量
            Long invitataionLikeCount = likeService.getInvitataionLikeCount(2, commentVo.getCommentEntity().getId());

            commentVo.setLikeCount(invitataionLikeCount);
            //给一个默认值
            commentVo.setLikeStatus(0);
            if (userEntity != null) {
                //已经登录了 查询当前用户是否给评论点赞了
                Boolean invitataionUserLike = likeService.getInvitataionUserLike(2, userEntity.getId(), commentVo.getCommentEntity().getId());
                commentVo.setLikeStatus(invitataionUserLike ? 1 : 0);
            }

            Integer cid = commentVo.getCommentEntity().getId();

            //查询评论下面的回复
            List<CommentVo> replyList = (baseMapper.commentListByInvitataionId(2, cid)); // 评论下面的回复列表
            for(CommentVo replyVo:replyList){
                Long count = likeService.getInvitataionLikeCount(2, replyVo.getCommentEntity().getId());
                replyVo.setLikeCount(count);
                if (userEntity != null) {
                    //查询当前用户是否给评论里的回复点赞了
                    Boolean invitataionUserLike = likeService.getInvitataionUserLike(2, userEntity.getId(), replyVo.getCommentEntity().getId());
                    replyVo.setLikeStatus(invitataionUserLike ? 1 : 0);
                }
            }
            commentVo.setReplyList(replyList);//查的是回复
        }

        return commentVoList;
    }

     @Override
     public Long getInvitationCommentSize(Integer id) {
         QueryWrapper wrapper = new QueryWrapper();
         wrapper.eq("entity_type", 1); // 给帖子的评论
         wrapper.eq("entity_id", id); // 给帖子的评论
         return baseMapper.selectCount(wrapper);
    }
}
